package com.fingard.dsp.bank.directbank.bfb01;

import java.util.HashMap;
import java.util.Map;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectHelper;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;

public class BFB01SinglePay extends BFB01Base implements ISinglePay {

	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail;
		tmpRetDetail = d_190802(p_req1908, retAts);

		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
		}
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	private RetAtsSglDetail d_190802(ReqSingle p_req1908, RetAtsSingle retAts) throws Exception {
		RetAtsSglDetail retDetail = new RetAtsSglDetail();
		HashMap<String, String> sendMap=new HashMap<String, String>();
		// 取第三方商户
		ActSetItem actItem = getBankConfig().getActSetItem(p_req1908.singleDetail.payAct, "");
		if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
			RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
			tmpRetDetail.respCode = "0";
			if (actItem == null) {
				tmpRetDetail.respInfo = "未找到账号" + p_req1908.singleDetail.payAct + "的批量商户配置节点";
			} else {
				tmpRetDetail.respInfo = "账号" + p_req1908.singleDetail.payAct + "的证书文件不存在";
			}
			tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			tmpRetDetail.transState = PaymentState.FAIL_Payment;
			tmpRetDetail.payInfoCode = FailCode.E9981;
			return tmpRetDetail;
		}
		sendMap.put("version", "1.0");
		sendMap.put("transCode", "singlePayment");
		sendMap.put("signType", "01");
		sendMap.put("merchantId", actItem.merchantId);
		sendMap.put("mcSequenceNo", p_req1908.singleDetail.askNumber);
		sendMap.put("mcTransDateTime", Format.DateTime14Format.format(p_req1908.singleDetail.getPayDateTime()));
		
		if (p_req1908.singleDetail.isPrivate.equals("1")) {
			if (p_req1908.singleDetail.cardType.equals("1")) {
				sendMap.put("accType",  "1");
			} else {
				sendMap.put("accType",  "0");
			}
		} else if (p_req1908.singleDetail.isPrivate.equals("2")) {
			sendMap.put("accType",  "2");
		}
		sendMap.put("bankCode",p_req1908.singleDetail.recBankCode);
		sendMap.put("lBnkNo",p_req1908.singleDetail.cnapsCode);
		sendMap.put("lBnkNam", p_req1908.singleDetail.recBankName);
		sendMap.put("validPeriod",p_req1908.singleDetail.expiredDate);
		sendMap.put("cvv2",p_req1908.singleDetail.cvv2);
		sendMap.put("remark",p_req1908.singleDetail.memo);
		sendMap.put("bnkRsv",p_req1908.singleDetail.purpose);
		sendMap.put("capUse","00");
		if(p_req1908.reqHeader.commandCode.equals("190802A")){//00：普通单笔      01：实时单笔
			sendMap.put("busType", "00");
		}
		else{
			sendMap.put("busType", "01");
		}
		nodeAnalysis(p_req1908.singleDetail.srcXElement, sendMap, getCharset());
		
		//sendMap.put("orderNo", p_req1908.singleDetail.askNumber);
		//订单号orderNo,需要商户号+请求日期+业务号进行拼接,即商户号+年月日（系统日期）ATS传过来的SourceNote（唯一业务号）
		String orderNo = actItem.merchantId+Format.Date8Format.format(p_req1908.singleDetail.getPayDateTime())+p_req1908.singleDetail.sourceNote;
		sendMap.put("orderNo", orderNo);
		
		StringBuilder sbLog = new StringBuilder();
		boolean saved = DirectHelper.saveReqSeqIDMapping(p_req1908.reqHeader.bankCode,p_req1908.reqHeader.transType, p_req1908.singleDetail.getPayDateOnly(), p_req1908.singleDetail.askNumber, orderNo, sbLog);
		if(!saved){
			retDetail.respCode = "0";
			retDetail.respInfo = sbLog.toString();
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = FailCode.E9981;
			return retDetail;
		}
		
		sendMap.put("amount", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount));
		sendMap.put("cardNo", p_req1908.singleDetail.recAct);
		sendMap.put("accName",  p_req1908.singleDetail.recName);

		String[] tmpStrRet = sendToBank(sendMap, actItem);// 发送银行
		// 处理银行返回的数据
		if (tmpStrRet[0].length() == 0) {
			Map<String, String> map = getRet(tmpStrRet[1]);
			if (map != null && map.size() != 0) {
				retDetail.respCode = "0";
				retDetail.respInfo = map.get("respMsg");
				retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
				retDetail.transState = map.get("respCode");
				retDetail.payInfoCode = retDetail.transState;
			} else {
				retDetail.respCode = "-1";
				retDetail.respInfo = "返回数据格式错误";
			}
		} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
			retDetail.respCode = "0";
			retDetail.respInfo = tmpStrRet[1];
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = tmpStrRet[0];
		}
		else if (tmpStrRet[0].equals("E9981")) {
			retDetail.respCode = "0";
			retDetail.respInfo = tmpStrRet[1];
			retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
			retDetail.transState = PaymentState.FAIL_Payment;
			retDetail.payInfoCode = tmpStrRet[0];
		}
		else {
			retDetail.respCode = "-1";
			retDetail.respInfo = tmpStrRet[1];
		}
		return retDetail;
	}


	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		// 返回ATS的对象
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
		HashMap<String, String> sendMap=new HashMap<String, String>();
		sendMap.put("version", "1.0");
		sendMap.put("transCode", "orderQuery");
		sendMap.put("signType", "01");
		// 取第三方商户
		ActSetItem actItem = getBankConfig().getActSetItem(p_req1944.payAct, "");
		if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)) {
			tmpRetAtsDetail.respCode = "-1";
			if (actItem == null) {
				tmpRetAtsDetail.respInfo = "未找到账号" + p_req1944.payAct + "的批量商户配置节点";
			} else {
				tmpRetAtsDetail.respInfo = "账号" + p_req1944.payAct + "的证书文件不存在";
			}
			tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
			//tmpRetAtsDetail.transState = PaymentState.FAIL_Batch;
			//tmpRetAtsDetail.payInfoCode = FailCode.E9981;
			retAts.writeRetDetail(tmpRetAtsDetail);
			return retAts;
		}
		sendMap.put("merchantId", actItem.merchantId);
		sendMap.put("mcTransDateTime",  Format.DateTime14Format.format(p_req1944.getBgnDateTime()));
		
		//sendMap.put("orderNo", p_req1944.askNumber);
		String toBankSeq = DirectHelper.getReqSeqIDMapping(p_req1944.askNumber);
		if(StringHelper.hasAnyChar(toBankSeq)){
			sendMap.put("orderNo", toBankSeq);
		}
		else{
			sendMap.put("orderNo", p_req1944.askNumber);
		}
		
		sendMap.put("amount", StringHelper.amountMultiply100(p_req1944.payAmount));
		try {
			String[] tmpStrRet = sendToBank(sendMap, actItem);
			if (tmpStrRet[0].length() == 0) {
				Map<String, String> map = getRet(tmpStrRet[1]);
				if (map != null && map.size() != 0) {
					// 受理成功
					if (map.get("respCode").equals("B0")) {
						if (map.get("orderNo").equals(p_req1944.askNumber) || (StringHelper.hasAnyChar(toBankSeq) && map.get("orderNo").equals(toBankSeq))) {
							tmpRetAtsDetail.respCode = "0";
							tmpRetAtsDetail.respInfo = map.get("ordMsg");
							tmpRetAtsDetail.transState = map.get("respCode") + "+" + map.get("ordSts");
							tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
							tmpRetAtsDetail.payInfoCode = map.get("ordSts");
						} else {
							tmpRetAtsDetail.respCode = "-1";
							tmpRetAtsDetail.respInfo = "返回的流水号" + map.get("orderNo") + "与请求" + p_req1944.askNumber
									+ "不符";
						}
					} else {
						tmpRetAtsDetail.respCode = "-1";
						tmpRetAtsDetail.respInfo = map.get("respMsg");
					}
				} else {
					tmpRetAtsDetail.respCode = "-1";
					tmpRetAtsDetail.respInfo = "返回数据格式错误";
				}
			} else {
				tmpRetAtsDetail.respCode = "-1";
				tmpRetAtsDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetAtsDetail.respCode = "-1";
			tmpRetAtsDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		retAts.writeRetDetail(tmpRetAtsDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
